package org.flexharmony.harmonizer.utils;

import java.util.List;

import org.flexharmony.harmonizer.javadef.JavaVisibility;
import org.objectweb.asm.Opcodes;

/**
 * Common methods used throughout the project.
 * 
 * @author Corey Baswell
 */
public class CommonMethods
{
  /**
   * Returns true if both objects are null, or if obj1 is not null and
   * obj1.equals(ob2) is true. Otherwise false is returned.
   */
  static public boolean nullEquals(Object obj1, Object obj2)
  {
    if ((obj1 == null) && (obj2 == null))
    {
      return true;
    }
    else if (obj1 == null)
    {
      return false;
    }
    else
    {
      return obj1.equals(obj2);
    }
  }

  /**
   * Returns true if the given list is null or emtpy.
   */
  static public boolean nullEmpty(List list)
  {
    return ((list == null) || (list.size() == 0));
  }
  
  /**
   * Converts the given byte qualified type name to a more readable qualified
   * name. For example:
   * 
   * "Ljava/lang/Integer;" would become "java.lang.Integer"
   */
  static public String convertByteCodeTypeName(String typeName)
  {
    if (typeName.indexOf('L') == 0)
    {
      typeName = typeName.substring(1, typeName.length());
    }
    
    typeName = typeName.replaceAll(";", "");
    return typeName.replaceAll("/", ".");
  }
  
  /**
   * Converts the given bytecode access to a {@link JavaVisibility} value.
   * 
   * @see Opcodes
   */
  static public JavaVisibility getVisiblity(int access)
  {
    if ((access & Opcodes.ACC_PRIVATE) != 0)
    {
      return JavaVisibility.PRIVATE;
    }
    else if ((access & Opcodes.ACC_PROTECTED) != 0)
    {
      return JavaVisibility.PROTECTED;
    }
    else if ((access & Opcodes.ACC_PUBLIC) != 0)
    {
      return JavaVisibility.PUBLIC;
    }
    else
    {
      return JavaVisibility.PACKAGE;
    }
  }
}
